/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */

$(function () {
    org.breezee.page = {
        init: function () {
            Dolphin.form.parse();
            this.initEvent();

            let shopCondition = {"category_in" : "1"};
            let _this = $("#cusCode");
            Dolphin.ajax({
                url: '/api/742445c653654caaa4a1fa69eb651a9a',
                type: Dolphin.requestMethod.POST,
                async : false,
                data: Dolphin.json2string({properties : shopCondition}),
                onSuccess: function (reData) {
                    _this.append(
                        '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                    $.each(reData.rows,function(index,obj){
                        _this.append(
                            '<option value="' + obj.id + '">'
                            + obj.name + '</option>');
                    });
                }
            });
            $(".js-example-basic-single").select2();

            this._userList = this.channelList('#userList');
            this._customerList = this.customerList("#customerList");
            this._accountList = this.accountList("#accountList");
            this._selectList = this.selectUserList('#selectedList');
            this._unSelectList = this.unSelectUserList('#unselectedList');
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            var me = this;
            $(".newAccount").click(function () {
                Dolphin.form.empty('.edit-form');
                $('#account_win').modal('show');
            });

            $(".vendorCustomer").click(function () {
                var checked = me._userList.getChecked();
                if (checked.length == 0) {
                    Dolphin.alert(Dolphin.i18n.get("distributor.selectCDistributor"));
                    return;
                }
                Dolphin.form.empty('.cus-form');
                Dolphin.form.setValue({
                    vendor: {
                        id: checked[0].id
                    },
                    profit: checked[0].profit
                }, '.cus-form');
                $('#customer_win').modal('show');
            });

            $(".vendorAccount").click(function () {
                var checked = me._userList.getChecked();
                if (checked.length == 0) {
                    Dolphin.alert(Dolphin.i18n.get("distributor.selectCDistributor"));
                    return;
                }
                $("#org_relation_win").modal('show');
            });

            /**
             * 保存按钮
             */
            $(".btn_submit").click(function () {
                var ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    var data = Dolphin.form.getValue(ef, '"');
                    data.type = 0;
                    data.level = '1';
                    Dolphin.ajax({
                        url: '/api/c477f55806ed4b3f934c3a21f8788dde',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._userList.load();
                            $('#account_win').modal('hide');
                        }
                    });

                }
            });

            $(".cus_submit").click(function () {
                var ef = $(".cus-form");
                if (Dolphin.form.validate(ef)) {
                    var data = Dolphin.form.getValue(ef, '"');
                    data.type = 0;
                    Dolphin.ajax({
                        url: '/api/9d2a3c8581aa4338bb8bf17f8c7def9a',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._customerList.load('/api/9d2a3c8581aa4338bb8bf17f8c7def9a', {
                                "vendor_id_object_ae": me.selectData.id
                            });
                            $('#customer_win').modal('hide');
                        }
                    });

                }
            });

            $('.relation_submit').click(function () {
                var data = {};
                data.id = me.selectData.id;
                data.accounts = [];
                var selData = me._selectList.data.rows;
                for (var i = 0; i < selData.length; i++) {
                    data.accounts.push({id: selData[i].id});
                }
                Dolphin.ajax({
                    url: '/api/01783cc1c81f4e52989dd06ad0e6376b',
                    type: Dolphin.requestMethod.POST,
                    data: Dolphin.json2string(data),
                    onSuccess: function (reData) {
                        me._accountList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                            "vendor_id_obj_ae": me.selectData.id
                        });
                        $('#org_relation_win').modal('hide');
                    }
                });
            });

            $('.content-refresh').click(function () {
                me._userList.reload();
            });

            $(".btn-query").click(function () {
                me._userList.load('', Dolphin.form.getValue('.query-form'));
            });

            $('[change]').click(function () {
                var thisButton = $(this), allFlag = !!thisButton.attr('all'),
                    sourceList, targetList,
                    checkedData,
                    i;
                if (thisButton.attr("change") == "select") {
                    sourceList = me._unSelectList;
                    targetList = me._selectList;
                } else {
                    sourceList = me._selectList;
                    targetList = me._unSelectList;
                }
                if (allFlag) {
                    checkedData = [].concat(sourceList.data.rows);
                } else {
                    checkedData = sourceList.getChecked();
                }
                for (i = 0; i < checkedData.length; i++) {
                    if (!checkedData[i].inheritFlag) {
                        sourceList.removeRow(checkedData[i].__id__);
                        targetList.addRowWithData(checkedData[i]);
                    }
                }
            });

            $('#org_relation_win').on('show.bs.modal', function (e) {
                me._selectList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                    "vendor_obj": me.selectData.id,
                    "pageSize": "-1"
                });
                me._unSelectList.load('/api/756af3ae31a64565a54ec0221f84d377', {"vendor_obj_not": me.selectData.id});
            });
        },
        channelList: function (panelId) {
            var me = this;
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("tenant.CDName"),
                    width: '150px'
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("tenant.CDCode"),
                    width: '110px'
                }, {
                    code: 'contactPerson',
                    title: Dolphin.i18n.get("framework.contactPerson"),
                    width: '110px'
                }, {
                    code: 'mobile',
                    title: Dolphin.i18n.get("framework.telephone"),
                    width: '90px'
                }, {
                    code: 'email',
                    title: Dolphin.i18n.get("framework.email"),
                    width: '110px'
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '110px',
                    formatter: function (val, row, index) {
                        return org.breezee.buttons.edit({
                            id: row.id
                        });
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/c477f55806ed4b3f934c3a21f8788dde',
                pagination: true,
                onLoadSuccess: function () {
                    org.breezee.buttons.editCallback('2315af794bbd432fbee70f533e8cdbad', 'id', function (data) {
                        $('#account_win').modal('show');
                    });
                },
                onChecked: function (data) {
                    me.selectData = data;
                    me._customerList.load('/api/9d2a3c8581aa4338bb8bf17f8c7def9a', {
                        "vendor_id_obj_ae": data.id
                    });
                    me._accountList.load('/api/756af3ae31a64565a54ec0221f84d377', {
                        "vendor_id_obj_ae": data.id
                    })
                }
            });
        },
        customerList: function (panelId) {
            var me = this;
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                title: Dolphin.i18n.get("distributor.channelCustomers"),
                columns: [{
                    code: 'customerName',
                    title: Dolphin.i18n.get("framework.clientName")
                }, {
                    code: 'profit',
                    title: Dolphin.i18n.get("distributor.rebate"),
                    textAlign:'right',
                    width: '90px'
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '110px',
                    formatter: function (val, row, index) {
                        return '<a class="btn btn-outline btn-circle btn-sm dark delBtn" data-id="'+row.id+'" href="javascript:;">' +
                            '<i class="fa fa-trash-o"></i>&nbsp;'+Dolphin.i18n.get("role.delete")+'</a>';
                    }
                }],
                multiple: true,
                rowIndex: true,
                checkbox: false,
                ajaxType: Dolphin.requestMethod.POST,
                data:{rows:[]},
                pagination: true,
                onLoadSuccess: function () {
                    org.breezee.buttons.delCallback('ef0c2078100c40f4bd28342f5c2bf41b', function (data) {
                        me._customerList.load('/api/9d2a3c8581aa4338bb8bf17f8c7def9a', {
                            "vendor_id_object_ae": me.selectData.id
                        });
                    });
                }
            });
        },

        accountList: function (panelId) {
            var me = this;
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                idField: 'id',
                panelType:'panel-info',
                title: Dolphin.i18n.get("distributor.associatedAccount"),
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("account.accountName")
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("account.accountCode"),
                    textAlign:'right',
                    width: '100px'
                }],
                multiple: true,
                rowIndex: true,
                checkbox: false,
                ajaxType: Dolphin.requestMethod.POST,
                data:{rows:[]},
                pagination: false,
                onLoadSuccess: function () {

                }
            });
        },

        selectUserList: function (panelId) {
            return new Dolphin.LIST({
                panel: panelId,
                panelType: 'panel-warning',
                title: Dolphin.i18n.get("role.selectedList"),
                idField: 'id',
                maxHeight: '400px',
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("role.userName"),
                    width: '120px'
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("role.userCode"),
                    width: '100px'
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: false
            });
        },
        unSelectUserList: function (panelId) {
            return new Dolphin.LIST({
                panel: panelId,
                title: Dolphin.i18n.get("role.unselectedList"),
                panelType: 'panel-info',
                maxHeight: '650px',
                idField: 'id',
                columns: [{
                    code: 'name',
                    title: Dolphin.i18n.get("role.userName"),
                    width: '120px'
                }, {
                    code: 'code',
                    title: Dolphin.i18n.get("role.userCode"),
                    width: '100px'
                }],
                multiple: true,
                rowIndex: false,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                data: {rows: []},
                pagination: true
            });
        }


    };
    org.breezee.page.init();
});